package cn.tedu.jxdm.controller;

import cn.tedu.jxdm.mapper.PostsMapper;
import cn.tedu.jxdm.pojo.dto.PostsDTO;
import cn.tedu.jxdm.pojo.entity.Posts;
import cn.tedu.jxdm.pojo.vo.UserVO;
import cn.tedu.jxdm.pojo.vo.PostsDetailVO;
import cn.tedu.jxdm.pojo.vo.PostsIndexVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/posts/")
public class PostsController {
    @Autowired(required = false)
    PostsMapper mapper;

    @RequestMapping("insert")
    public int insert(@RequestBody PostsDTO postsDTO, HttpSession session){
        //从会话对象中得到登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        if (user==null){//未登录
            return 2;
        }
        Posts w = new Posts();
        //复制属性
        BeanUtils.copyProperties(postsDTO,w);
        w.setCreated(new Date());
        //设置微博对象中用户id为当前登录的用户id
        w.setUserId(user.getId());
        mapper.insert(w);
        return 1;
    }
    @RequestMapping("selectIndex")
    public List<PostsIndexVO> selectIndex(){
        return mapper.selectIndex();
    }
    @RequestMapping("selectById")
    public PostsDetailVO selectById(int id){
        return mapper.selectById(id);
    }
}
